package com.yqg.demo.task;

import com.sourceforge.snap7.moka7.S7;
import com.sourceforge.snap7.moka7.S7Client;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author suzhuang
 * @ClassName: TalkReceive
 * @Function: TODO
 * @Date: 2023/5/9 20:41
 */
@Data
@Slf4j
public class TalkReceive implements Runnable {
    DatagramSocket socket = null;
    private String msgFrom;
    private String sendUrl;
    private String message;
    private int byteNum;
    private int amount;
    public static S7Client s7Client;
    public static byte[] newbytes;

    public TalkReceive(String msgFrom, String sendUrl, int byteNum, int amount) {
        this.msgFrom = msgFrom;
        this.sendUrl = sendUrl;
        this.byteNum = byteNum;
        this.amount = amount;
    }


    @Override
    public void run() {
        s7Client = new S7Client();
//        boolean flag = false;
        while (true) {
            int i = s7Client.ConnectTo("192.168.0.2", 0, 2);
            if (i != 0) {
//                flag = true;
                log.info("连接成功");
                break;
            } else {
                String communication = "CommunicationException";
                sendDatatoyc(communication.getBytes());
                log.info("连接失败");
            }
        }
        try {
            while (true) {
                newbytes = new byte[byteNum];
                // 参数依次为(读取DB块(固定),DB块编号，偏移量，字节大小，读取到的数据存入的地址)
                int i = s7Client.ReadArea(S7.S7AreaDB, 152, 0, amount, newbytes);
//                for (int j = 0; j < newbytes.length; j++) {
//                    for (int k = 0; k < 8; k++) {
//                        System.out.println(S7.GetBitAt(newbytes, j, k));
//                    }
//                }
                if (i == 0) {
                    sendDatatoyc(newbytes);
                    Thread.sleep(2000);
                } else {
                    String communication = "CommunicationException";
                    sendDatatoyc(communication.getBytes(StandardCharsets.UTF_8));
                    log.info("获取plc数据失败");
                    Thread.sleep(1000);
                    run();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }


    /**
     * 发送数据到外网系统
     */
    private void sendDatatoyc(byte[] newbytes) {
        try {
            socket = new DatagramSocket();    //建立套接字   124.167.249.190
            DatagramPacket packet = new DatagramPacket(newbytes, 0, newbytes.length, new InetSocketAddress(sendUrl, 9900));
            socket.send(packet);    //发送数据包
            log.info("【" + new Date() + "】发送消息到外网系统{},：{}", sendUrl, newbytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

